package com.fx.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fx.usercenter.common.ErrorCode;
import com.fx.usercenter.exception.BusinessException;
import com.fx.usercenter.service.UserService;
import com.fx.usercenter.model.domain.User;
import com.fx.usercenter.mapper.UserMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.fx.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
* @author Administrator
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-07-27 15:31:20
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource UserMapper userMapper;

    public final String SALT = "feixiang";
    /**
     * 注册用户
     * @param userAccount
     * @param userPassword
     * @param plantCode
     * @return
     */
    @Override
    public long Register(String userAccount, String userPassword, String plantCode) {
        //注册用户输入账号，密码，星球编号
        //1.账号长度不小于4，密码长度不小于8，账号不能有特殊字符
        if(StringUtils.isAllBlank(userAccount,userPassword,plantCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userPassword.length() < 4 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.账号名不能重复
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        //count 计数
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //3.对密码进行加密
        String entryPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //4.向数据库加入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(entryPassword);
        user.setPlanetCode(plantCode);
        int result = userMapper.insert(user);
        if (result < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return user.getId();
    }

    /**
     * 登录
     * @param userAccount
     * @param userPassword
     * @return
     */
    //记录用户登录态
    @Override
    public User Login(String userAccount, String userPassword, HttpServletRequest request) {
        if(StringUtils.isAllBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userPassword.length() < 4 ){
           throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String entryPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",entryPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
           log.info("user login failed");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //用户状态判断 0:正常 1:不可用
        if (user.getUserStatus() == 1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //记录用户登录态,将信息存入session!!!,第二次才知道
        //我先暂时不脱敏
        //request.getSession().setAttribute(USER_LOGIN_STATE,safeUser(user));
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        //return safeUser(user);
        return user;
    }

    /**
     * 查用户
     * @return
     */
    @Override
    public List findUsers() {
        QueryWrapper queryWrapper = new QueryWrapper();
        List userList = userMapper.selectList(queryWrapper);
        //测试内存查询,引用序列化      暂时用不到   Gson gson = new Gson();
        Stream<User> stream = userList.stream();
        //对流中每个元素进行脱敏
        return stream.map(this::safeUser).collect(Collectors.toList());
    }

    /**
     * 逻辑删除用户
     * @param id
     * @return
     */
    @Override
    public long deleteById(int id) {
    User user = userMapper.selectById(id);
    userMapper.deleteById(user);
     return user.getId();
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @Override
    public long loginOut(HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
      request.getSession().removeAttribute(USER_LOGIN_STATE);
        throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    /**
     * 更新信息
     * @param user
     * @return
     */
    @Override
    public long updateUser(User user,HttpServletRequest request) {
        if (request == null){
           throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //修改信息
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //看用户是否存在
        User slectuser = userMapper.selectById(user.getId());
        if (slectuser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return userMapper.updateById(user);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */

    @Override
    public int addUser(User user) {
      if (user == null){
          throw new BusinessException(ErrorCode.PARAMS_ERROR);
      }
      String entryPassword = DigestUtils.md5DigestAsHex((SALT+user.getUserPassword()).getBytes());
      user.setUserPassword(entryPassword);
        int result = userMapper.insert(user);
        return result;
    }

    /**
     * 分页查询测试
     *
     * @return
     */
    @Override
    public Page<User> limitSelectUsers() {
        Page<User> page = new Page<>(1,3);
        Page<User> pageUses = userMapper.selectPage(page, new QueryWrapper<>());
        return pageUses;
    }

    /**
     * 多添加查询
     * @param userName
     * @param gender
     * @return
     */
    @Override
    public List findUsers(String userName, int gender,HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        if(userName == null && gender !=3){
            //只按性别
           queryWrapper.eq("gender",gender);
           return userMapper.selectList(queryWrapper);
        }
        if(userName != null && gender !=3){
            //性别   用户名称
            queryWrapper.eq("gender",gender);
            queryWrapper.eq("userName",userName);
            return userMapper.selectList(queryWrapper);
        }
        if(userName != null && gender == 3){
            //只按用户名称
            queryWrapper.eq("userName",userName);
            return userMapper.selectList(queryWrapper);
        }
        //默认返回所有
        return userMapper.selectList(queryWrapper);
    }
    /**
     * 更改用户权限
     * @param userAccount
     * @param userRole
     * @param request
     * @return
     */
    @Override
    public long updateRole(String userAccount, int userRole, HttpServletRequest request) {
        if(request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        user.setUserRole(userRole);
        userMapper.updateById(user);
        return user.getId();
    }
    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    public User safeUser (User originUser) {
        User safetUser = new User();
        safetUser.setId(originUser.getId());
        safetUser.setUsername(originUser.getUsername());
        safetUser.setUserAccount(originUser.getUserAccount());
        safetUser.setAvatarUrl(originUser.getAvatarUrl());
        safetUser.setGender(originUser.getGender());
        safetUser.setPhone(originUser.getPhone());
        safetUser.setEmail(originUser.getEmail());
        safetUser.setUserRole(originUser.getUserRole());
        safetUser.setUserStatus(originUser.getUserStatus());
        safetUser.setPlanetCode(originUser.getPlanetCode());
        return safetUser;
    }
}




